<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grid;
use App\Models\GridImg;
use App\Models\ProtocolSet;
use App\Models\BuildForm;
use App\Models\GridArea;
use App\Models\GridHouse;
use App\Models\GridPrice;
use App\Models\GridAssess;
use App\Models\Villager;
use App\Models\ApprovalSet;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

// 结算/银行/发放
class GridPriceController extends Controller
{
    // 录入
    public function addPrice(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $grid_price = GridPrice::query()
        ->where('grid_id',$params['grid_id'])
        ->where('type',$params['type']-1)
        ->first();

        if(!$grid_price){
            return showError('未完成上一步，无法操作');
        }

        $Info['type']=$params['type'];
        $Info['grid_id']=$params['grid_id'];
        $Info['street_id']=$grid_price['street_id'];
        $Info['village_id']=$grid_price['village_id'];
        $Info['project_id']=$grid_price['project_id'];
        $Info['segment_id']=$grid_price['segment_id'];
        $Info['subsidy_fee']=$grid_price['subsidy_fee'];
        $Info['transition_fee']=$grid_price['transition_fee'];
        $Info['require_sign_fee']=$grid_price['require_sign_fee'];
        $Info['require_clear_fee']=$grid_price['require_clear_fee'];
        $Info['if_decorate_fee']=$grid_price['if_decorate_fee'];
        $Info['supply_total_fee']=$grid_price['supply_total_fee'];
        $Info['house_difference_fee']=$grid_price['house_difference_fee'];
        $Info['party_a_fee']=$grid_price['party_a_fee'];
        $Info['party_b_fee']=$grid_price['party_b_fee'];
        $Info['stop_fee']=$grid_price['stop_fee'];
        $Info['lack_area_fee']=$grid_price['lack_area_fee'];
        $Info['money_fee']=$grid_price['money_fee'];
        $Info['yard_fee']=$grid_price['yard_fee'];
        $Info['othe_build_fee']=$grid_price['othe_build_fee'];
        $Info['use_fee']=$grid_price['use_fee'];
        $Info['assess_fee']=$grid_price['assess_fee'];
        $Info['other_subsidy_fee']=$grid_price['other_subsidy_fee'];
        $Info['subsidiary_fee']=$grid_price['subsidiary_fee'];

        isset($params['pay_fee'])?$Info['pay_fee']=$params['pay_fee']:'';
        isset($params['pay_time'])?$Info['pay_time']=$params['pay_time']:'';
        isset($params['num'])?$Info['num']=$params['num']:'';
        isset($params['imgs'])?$Info['imgs']=$params['imgs']:'';

        $Info['do_user_id']=auth('api')->user()->id??0;

        try {
            $res=GridPrice::query()
            ->updateOrCreate(['grid_id'=>$params['grid_id'],'type'=>$params['type']],$Info);

            $template_arr=[1=>21,2=>22,3=>23];
            $grid=Grid::query()->select('project_id','street_id','village_id')->where('id',$params['grid_id'])->first();
            $approval_set=ApprovalSet::query()
            ->where('project_id',$grid['project_id']??2)
            ->where('street_id',$grid['street_id']??3)
            ->where('village_id',$grid['village_id']??1)
            ->where('template_id',$template_arr[$params['type']])
            ->where('status',1)
            ->value('id');
            $status=[1=>'settlement_status',2=>'bank_status',3=>'grant_status'];
            if($approval_set){//有审批
                Grid::query()->where('id',$params['grid_id'])->update([$status[$params['type']]=>2]);
                // 触发审批-完成 结算/银行/发放
                if(!$this->findApproval($params['grid_id'], $template_arr[$params['type']])){
                    $this->setApproval($params['grid_id'],$template_arr[$params['type']]);
                }
            }else{
                Grid::query()->where('id',$params['grid_id'])->update([$status[$params['type']]=>1]);
            }

            return showSuccess('提交成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
    }

    // 回显
    public function priceList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $type=$params['type'];

        $data=Grid::query()
        ->select('id','name','supply_form','build_form','street_id','village_id','project_id','segment_id','receive_villager_id','sign_num')
        ->where('id',$params['grid_id'])
        ->with('villager:name,identity_card,phone,grid_id')
        ->with('agent:name,identity_card,phone,grid_id')
        ->with(['grid_price'=> function ($query) use ($type) {
            $query->where('type', $type);
        }])
        ->first()
        ->toArray();

        if(empty($data['grid_price'])){
            $grid_price = GridPrice::query()
                ->where('grid_id',$params['grid_id'])
                ->where('type',$params['type']-1)
                ->first();

            if(!$grid_price){
                return showError('未完成上一步，无法操作');
            }

            $data['grid_price']=$grid_price;
            $data['grid_price']['pay_fee']=0;
            $data['grid_price']['pay_time']='';
            $data['grid_price']['num']='';
            $data['grid_price']['imgs']='';
        }
       
        $data['grid_price']['imgs']=$data['grid_price']['imgs']?$this->getImageUrl($data['grid_price']['imgs']):[];
        $data['build_form_name']=BuildForm::query()->where('id',$data['build_form'])->value('name');
        $data['receive_villager_name']=Villager::query()->where('id',$data['receive_villager_id'])->value('name');

        if(!$data['grid_price']){
            return showError('未查询到数据，无法操作');
        }
       
        unset($data['street_id']);
        unset($data['village_id']); 
        unset($data['project_id']);
        unset($data['segment_id']);

        return showData($data);
    }
}

